package com.lw.carmanage.security.handler;

import com.lw.carmanage.enums.LoginResultEnum;
import com.lw.carmanage.events.MyLoginEvent;
import com.lw.carmanage.mapper.SysRoleMapper;
import com.lw.carmanage.pojo.SysMenu;
import com.lw.carmanage.pojo.SysRole;
import com.lw.carmanage.security.BaseUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/29 21:52
 */
@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private ApplicationContext context;

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    private SysRoleMapper roleMapper;

    @Autowired
    public void setRoleMapper(SysRoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.getWriter().write("denglu chenggong");


        BaseUser baseUser = (BaseUser) authentication.getPrincipal();
        request.getSession().setAttribute("user",baseUser);//登录成功之后存到session中
        List<SysRole> roleList = roleMapper.findByUserIdAndMenu(baseUser.getUserId());
        Set<String> allPerms=new HashSet<>();
        roleList.forEach(sysRole -> {
            List<SysMenu> menuList = sysRole.getMenuList();
            List<String> permList = menuList.stream().filter(sysMenu -> sysMenu.getPerms()!=null).map(SysMenu::getPerms).collect(Collectors.toList());
            allPerms.addAll(permList);
        });

        List<SimpleGrantedAuthority> authorityList = allPerms.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //更新用户权限
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(baseUser,authentication.getCredentials(),authorityList));

        //添加登录成功日志
        context.publishEvent(new MyLoginEvent(LoginResultEnum.SUCCESS,baseUser.getUsername()));
    }
}
